package com.jim.healio.graphrag.service.impl;

import com.jim.healio.graphrag.model.MedicalEntity;
import com.jim.healio.graphrag.model.MedicalDocument;
import com.jim.healio.graphrag.model.DocumentSearchResult;
import com.jim.healio.graphrag.service.GraphRAGService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * GraphRAG服务的模拟实现
 * 用于开发和测试阶段，提供预定义的医学知识
 */
@Service
public class MockGraphRAGServiceImpl implements GraphRAGService {
    
    private static final Logger logger = LoggerFactory.getLogger(MockGraphRAGServiceImpl.class);
    
    @Override
    public List<MedicalEntity> queryEntities(String query) {
        logger.info("模拟查询医学实体: {}", query);
        
        List<MedicalEntity> results = new ArrayList<>();
        
        if (query.contains("糖尿病") || query.contains("diabetes")) {
            results.add(new MedicalEntity("diabetes_1", "2型糖尿病", 
                MedicalEntity.EntityType.DISEASE, 
                "最常见的糖尿病类型，占糖尿病患者的90%以上"));
            
            results.add(new MedicalEntity("insulin_1", "胰岛素", 
                MedicalEntity.EntityType.DRUG, 
                "用于治疗糖尿病的激素药物"));
        }
        
        if (query.contains("高血压") || query.contains("hypertension")) {
            results.add(new MedicalEntity("hypertension_1", "原发性高血压", 
                MedicalEntity.EntityType.DISEASE, 
                "成人收缩压≥140mmHg和/或舒张压≥90mmHg"));
                
            results.add(new MedicalEntity("acei_1", "ACEI类药物", 
                MedicalEntity.EntityType.DRUG, 
                "血管紧张素转换酶抑制剂，用于降血压"));
        }
        
        if (query.contains("头痛") || query.contains("headache")) {
            results.add(new MedicalEntity("headache_1", "偏头痛", 
                MedicalEntity.EntityType.SYMPTOM, 
                "反复发作的搏动性头痛"));
                
            results.add(new MedicalEntity("tension_headache_1", "紧张性头痛", 
                MedicalEntity.EntityType.SYMPTOM, 
                "最常见的头痛类型，呈束带样压迫感"));
        }
        
        return results;
    }
    
    @Override
    public List<DocumentSearchResult> semanticSearch(String query, int limit) {
        logger.info("模拟语义搜索文档: {}, 限制: {}", query, limit);
        
        List<DocumentSearchResult> results = new ArrayList<>();
        
        if (query.contains("糖尿病")) {
            results.add(new DocumentSearchResult(
                "ada_guideline_2024", 
                "ADA糖尿病诊疗指南2024", 
                "对于2型糖尿病患者，推荐首选二甲双胍作为一线治疗药物。如果患者有心血管疾病风险，可考虑联用SGLT-2抑制剂或GLP-1受体激动剂。", 
                0.92
            ));
            
            results.add(new DocumentSearchResult(
                "diabetes_complications", 
                "糖尿病并发症防治指南", 
                "糖尿病肾病是糖尿病的主要微血管并发症之一。早期干预包括血糖控制、血压管理（目标<130/80mmHg）和使用ACEI/ARB类药物。", 
                0.85
            ));
        }
        
        if (query.contains("高血压")) {
            results.add(new DocumentSearchResult(
                "hypertension_guideline", 
                "中国高血压防治指南", 
                "高血压的非药物治疗包括减少钠盐摄入、控制体重、规律运动、戒烟限酒。药物治疗首选ACEI、ARB、利尿剂、钙通道阻滞剂中的任意一种。", 
                0.89
            ));
        }
        
        if (query.contains("药物相互作用")) {
            results.add(new DocumentSearchResult(
                "drug_interactions", 
                "临床药物相互作用手册", 
                "华法林与阿司匹林联用时出血风险显著增加，需要密切监测INR值和临床出血征象。建议调整华法林剂量并定期复查凝血功能。", 
                0.88
            ));
        }
        
        // 限制结果数量
        return results.subList(0, Math.min(results.size(), limit));
    }
    
    @Override
    public List<DocumentSearchResult> hybridSearch(String query, List<String> entityIds, int limit) {
        logger.info("模拟混合搜索: {}, 实体: {}, 限制: {}", query, entityIds, limit);
        
        // 简单实现：结合实体过滤和语义搜索
        List<DocumentSearchResult> semanticResults = semanticSearch(query, limit * 2);
        List<DocumentSearchResult> filteredResults = new ArrayList<>();
        
        for (DocumentSearchResult result : semanticResults) {
            // 模拟实体匹配逻辑
            if (entityIds == null || entityIds.isEmpty()) {
                filteredResults.add(result);
            } else {
                for (String entityId : entityIds) {
                    if (result.getContent().contains(getEntityName(entityId))) {
                        result.addMatchedEntity(entityId);
                        filteredResults.add(result);
                        break;
                    }
                }
            }
        }
        
        return filteredResults.subList(0, Math.min(filteredResults.size(), limit));
    }
    
    @Override
    public List<DocumentSearchResult> queryDocumentsByEntity(String entityId, int limit) {
        logger.info("模拟根据实体查询文档: {}, 限制: {}", entityId, limit);
        
        String entityName = getEntityName(entityId);
        return semanticSearch(entityName, limit);
    }
    
    @Override
    public List<MedicalEntity> analyzeSymptomRelations(List<String> symptoms) {
        logger.info("模拟分析症状关联: {}", symptoms);
        
        List<MedicalEntity> results = new ArrayList<>();
        
        // 模拟症状关联分析
        if (symptoms.contains("头痛") && symptoms.contains("发热")) {
            results.add(new MedicalEntity("meningitis_1", "脑膜炎", 
                MedicalEntity.EntityType.DISEASE, 
                "脑膜炎症，常见症状包括头痛、发热、颈项强直"));
        }
        
        if (symptoms.contains("胸痛") && symptoms.contains("呼吸困难")) {
            results.add(new MedicalEntity("myocardial_infarction_1", "心肌梗死", 
                MedicalEntity.EntityType.DISEASE, 
                "冠状动脉急性闭塞导致的心肌坏死"));
        }
        
        return results;
    }
    
    @Override
    public List<MedicalEntity> queryDrugInteractions(List<String> drugs) {
        logger.info("模拟查询药物相互作用: {}", drugs);
        
        List<MedicalEntity> results = new ArrayList<>();
        
        if (drugs.contains("华法林") && drugs.contains("阿司匹林")) {
            MedicalEntity interaction = new MedicalEntity("warfarin_aspirin_interaction", 
                "华法林-阿司匹林相互作用", 
                MedicalEntity.EntityType.DRUG, 
                "两药联用时出血风险显著增加，需要密切监测凝血功能");
            interaction.getProperties().put("risk_level", "高风险");
            interaction.getProperties().put("monitoring_required", true);
            results.add(interaction);
        }
        
        return results;
    }
    
    @Override
    public List<DocumentSearchResult> getTreatmentGuidelines(String condition) {
        logger.info("模拟获取治疗指南: {}", condition);
        
        return semanticSearch(condition + " 治疗指南", 5);
    }
    
    @Override
    public void storeDocument(MedicalDocument document) {
        logger.info("模拟存储文档: {}", document.getTitle());
        // 模拟存储操作
    }
    
    @Override
    public void storeEntity(MedicalEntity entity) {
        logger.info("模拟存储实体: {}", entity.getName());
        // 模拟存储操作
    }
    
    /**
     * 根据实体ID获取实体名称（模拟）
     */
    private String getEntityName(String entityId) {
        switch (entityId) {
            case "diabetes_1": return "糖尿病";
            case "hypertension_1": return "高血压";
            case "insulin_1": return "胰岛素";
            case "acei_1": return "ACEI";
            default: return entityId;
        }
    }
} 